package com.app.babygo;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

import com.app.babygo.dbservice.UserAdapter;
import com.app.babygo.help.ActionHelper;
import com.app.babygo.help.MessageHelper;
import com.app.babygo.help.SqlServerHelper;
import com.app.babygo.obj.User;

public class Register extends Activity {
	
	protected static final String TAG = "UserRegister_UI";
	public static String currentUserId = "";
	public final static String USERTITLE_MESSAGE = "com.app.babygo.MESSAGE";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.register, menu);
		return true;
	}

	public void completeRegister(View view) {

		//get data from UI
		EditText userid = (EditText) findViewById(R.id.register_username);
		String uid = userid.getText().toString();
		EditText password = (EditText) findViewById(R.id.register_password);
		String pwd = password.getText().toString();
		EditText password_confirm = (EditText) findViewById(R.id.register_password_confirm);
		String pwd_conf = password_confirm.getText().toString();
		
		//check validation
		if(uid.equalsIgnoreCase("")){
			MessageHelper.showMsg(this, "Register infomation error", "User Id is empty");
			return;
		} else if(!pwd.equalsIgnoreCase(pwd_conf) || pwd.equalsIgnoreCase("")){
			MessageHelper.showMsg(this, "Register infomation error", "Password does not match with confirm");
			return;
		}
		
		User newUser = new User(uid, pwd, ActionHelper.DefaultAccessLevel);
		currentUserId = newUser.getUserid();
		if(!UserValidation(newUser)){
			MessageHelper.showMsg(this, "User id", "User or Pasword contain illegal charactor");
			return;
		} else {
			try{
				UserAdapter db = new UserAdapter(this);
				db.open();
				db.initialAccount(newUser);
				db.close();
				// Add child to MySql Db
				SqlServerHelper sql = new SqlServerHelper();
				sql.SycServer(newUser);
			} catch (Exception e){
				e.printStackTrace();
			} 
			Intent intent = new Intent(this, ChildCreation.class);
			startActivity(intent);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		finish();
	}

	/**
	 * Help functions
	 */
	private boolean UserValidation(User userinfo) {
		
		//TODO; Blocked by ActionHelper functions
		boolean userValidation = ActionHelper.UserNameValidation(userinfo.getUserid());
		//boolean passwordValidation = ActionHelper.PasswordIDValidation(userinfo.getPassword());
		
		return !userValidation;
	}

}
